<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>求众数 II</title>
  </head>
  <body>
    <script>
      // 给定一个大小为 n 的整数数组，找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

      // 示例 1：
      // 输入：[3,2,3]
      // 输出：[3]
      // ---------------------------
      var majorityElement = function (nums) {
        let arr = [];
        let numsLen = nums.length;
        if (numsLen === 1) {
          arr.push(nums[0]);
          return arr;
        }
        let n = Math.floor(numsLen / 3);
        nums.sort(function (a, b) {
          return a - b;
        });
        let m = 0;
        for (let i = 1; i < numsLen; i++) {
          if (nums[m] !== nums[i]) {
            if (i - m > n) {
              arr.push(nums[m]);
            }
            m = i;
          }
          if (i === numsLen - 1) {
            if (i - m + 1 > n) {
              arr.push(nums[m]);
              break;
            }
          }
        }
        return arr;
      };

      console.log(majorityElement([3, 2, 3]));
    </script>
  </body>
</html>
